// src/components/TopicAdminPanel.js - 话题管理员面板组件

import React, { useState, useEffect } from 'react';
import {
  Modal, Button, Space, Input, List, Avatar, Popconfirm,
  message, Form, Typography, Divider, Card, Tag, Select
} from 'antd';
import {
  UserAddOutlined, UserDeleteOutlined, DeleteOutlined,
  CrownOutlined, SearchOutlined, ExclamationCircleOutlined
} from '@ant-design/icons';
import { topics } from '../services';
import { users } from '../services';

const { Title, Text } = Typography;
const { Search } = Input;
const { Option } = Select;

const TopicAdminPanel = ({
  visible,
  onClose,
  topic,
  currentUser,
  onTopicUpdate,
  onTopicDeleted
}) => {
  const [loading, setLoading] = useState(false);
  const [searchUserId, setSearchUserId] = useState('');
  const [topicMembers, setTopicMembers] = useState([]);
  const [membersLoading, setMembersLoading] = useState(false);
  const [allTopicUsers, setAllTopicUsers] = useState([]); // 保存所有话题用户(包括管理员)的完整信息

  // 获取话题成员列表
  const loadTopicMembers = async () => {
    if (!topic?.topicId) return;

    try {
      setMembersLoading(true);
      const response = await users.getTopicAllUsers(topic.topicId);

      if (response.success) {
        // 保存所有用户的完整信息（包括管理员）
        setAllTopicUsers(response.data);

        // 过滤掉已经是管理员的用户，用于添加管理员的下拉选择
        const nonAdminMembers = response.data.filter(member =>
          member.role === 'user' // 只显示普通成员，不显示已经是管理员的用户
        );
        setTopicMembers(nonAdminMembers);

        console.log('话题所有用户数据:', response.data);
      } else {
        console.warn('获取话题成员失败:', response.message);
        setTopicMembers([]);
        setAllTopicUsers([]);
      }
    } catch (error) {
      console.error('获取话题成员失败:', error);
      setTopicMembers([]);
      setAllTopicUsers([]);
    } finally {
      setMembersLoading(false);
    }
  };

  // 当Modal打开时加载话题成员
  useEffect(() => {
    if (visible && topic?.topicId) {
      loadTopicMembers();
    }
  }, [visible, topic?.topicId]);

  // 添加管理员
  const handleAddAdmin = async () => {
    if (!searchUserId) {
      message.warning('请选择要添加的用户');
      return;
    }

    try {
      setLoading(true);
      const response = await topics.addTopicAdmin(topic.topicId, parseInt(searchUserId));

      if (response.success) {
        message.success('管理员添加成功');
        setSearchUserId('');
        // 重新加载话题成员列表和话题信息
        await loadTopicMembers();
        onTopicUpdate(); // 通知父组件更新话题信息
      } else {
        message.error(response.message || '添加管理员失败');
      }
    } catch (error) {
      console.error('添加管理员失败:', error);
      message.error('添加管理员失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 移除管理员
  const handleRemoveAdmin = async (username) => {
    try {
      setLoading(true);

      // 从已加载的话题用户数据中查找对应的userId
      console.log('正在移除管理员:', username);
      console.log('所有话题用户数据:', allTopicUsers);

      const targetUser = allTopicUsers.find(user => user.username === username);

      if (!targetUser) {
        message.error(`无法找到用户 ${username} 的信息`);
        return;
      }

      const userId = targetUser.userId;
      console.log('用户名', username, '对应的用户ID:', userId, '角色:', targetUser.role);

      // 调用移除管理员API
      const response = await topics.removeTopicAdmin(topic.topicId, userId);

      if (response.success) {
        message.success('管理员移除成功');
        // 重新加载话题成员列表和话题信息
        await loadTopicMembers();
        onTopicUpdate(); // 通知父组件更新话题信息
      } else {
        message.error(response.message || '移除管理员失败');
      }
    } catch (error) {
      console.error('移除管理员失败:', error);
      message.error('移除管理员失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 删除话题
  const handleDeleteTopic = async () => {
    try {
      setLoading(true);
      const response = await topics.deleteTopic(topic.topicId);

      if (response.success) {
        message.success('话题删除成功');
        onClose();
        onTopicDeleted(); // 通知话题已被删除
      } else {
        message.error(response.message || '删除话题失败');
      }
    } catch (error) {
      console.error('删除话题失败:', error);
      message.error('删除话题失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 检查是否是话题拥有者
  const isTopicOwner = () => {
    const isOwner = currentUser && topic && currentUser.username === topic.creator;
    console.log('权限检查 - 是否是话题拥有者:', {
      currentUser: currentUser?.username,
      topicCreator: topic?.creator,
      isOwner
    });
    return isOwner;
  };

  // 检查是否是管理员
  const isAdmin = () => {
    return currentUser && (
      currentUser.role === 'admin' ||
      isTopicOwner() ||
      (topic?.moderators && topic.moderators.includes(currentUser.username))
    );
  };

  if (!topic || !isAdmin()) {
    return null;
  }

  return (
    <Modal
      title={
        <Space>
          <CrownOutlined />
          话题管理面板
        </Space>
      }
      open={visible}
      onCancel={onClose}
      footer={null}
      width={600}
    >
      <Card>
        {/* 话题信息 */}
        <div style={{ marginBottom: 24 }}>
          <Title level={4}>{topic.title}</Title>
          <Space wrap>
            <Tag color="blue">创建者: {topic.creator}</Tag>
            <Tag color="green">成员数: {topic.memberCount || 0}</Tag>
            <Tag color="orange">帖子数: {topic.postCount || 0}</Tag>
          </Space>
        </div>

        <Divider>管理员操作</Divider>

        {/* 添加管理员 */}
        {isTopicOwner() && (
          <div style={{ marginBottom: 24 }}>
            <Title level={5}>添加管理员</Title>
            <Text type="secondary" style={{ display: 'block', marginBottom: 8 }}>
              从话题成员中选择要提升为管理员的用户
            </Text>
            <Space.Compact style={{ width: '100%' }}>
              <Select
                placeholder="搜索并选择话题成员"
                value={searchUserId}
                onChange={setSearchUserId}
                style={{ flex: 1 }}
                loading={membersLoading}
                showSearch
                filterOption={(input, option) =>
                  option?.children.toLowerCase().includes(input.toLowerCase())
                }
                notFoundContent={membersLoading ? '加载中...' : '暂无可添加的成员'}
              >
                {topicMembers.map(member => (
                  <Option key={member.userId} value={member.userId}>
                    {member.username} (ID: {member.userId})
                  </Option>
                ))}
              </Select>
              <Button
                type="primary"
                icon={<UserAddOutlined />}
                onClick={handleAddAdmin}
                loading={loading}
                disabled={!searchUserId}
              >
                添加
              </Button>
            </Space.Compact>
            {topicMembers.length === 0 && !membersLoading && (
              <Text type="secondary" style={{ fontSize: 12, marginTop: 4, display: 'block' }}>
                当前话题中没有可以提升为管理员的普通成员
              </Text>
            )}
          </div>
        )}

        {/* 管理员列表 */}
        <div style={{ marginBottom: 24 }}>
          <Title level={5}>当前管理员</Title>
          {topic.moderators && topic.moderators.length > 0 ? (
            <List
              size="small"
              dataSource={topic.moderators}
              renderItem={(admin) => (
                <List.Item
                  key={admin}
                  actions={[
                    isTopicOwner() && admin !== topic.creator && (
                      <Popconfirm
                        title="确定要移除这个管理员吗？"
                        onConfirm={() => handleRemoveAdmin(admin)}
                        okText="确定"
                        cancelText="取消"
                      >
                        <Button
                          type="text"
                          size="small"
                          danger
                          icon={<UserDeleteOutlined />}
                        >
                          移除
                        </Button>
                      </Popconfirm>
                    )
                  ].filter(Boolean)}
                >
                  <List.Item.Meta
                    avatar={<Avatar size="small" icon={<CrownOutlined />} />}
                    title={
                      <Space>
                        <Text strong>{admin}</Text>
                        {admin === topic.creator && (
                          <Tag color="gold" size="small">拥有者</Tag>
                        )}
                      </Space>
                    }
                  />
                </List.Item>
              )}
            />
          ) : (
            <Text type="secondary">暂无其他管理员</Text>
          )}
        </div>

        {/* 危险操作 */}
        {isTopicOwner() && (
          <>
            <Divider>危险操作</Divider>
            <div style={{ textAlign: 'center' }}>
              <Popconfirm
                title="删除话题"
                description="此操作将永久删除话题及其所有帖子和评论，是否确认？"
                onConfirm={handleDeleteTopic}
                okText="确认删除"
                cancelText="取消"
                okType="danger"
                icon={<ExclamationCircleOutlined style={{ color: 'red' }} />}
              >
                <Button
                  danger
                  type="primary"
                  icon={<DeleteOutlined />}
                  loading={loading}
                  size="large"
                >
                  删除话题
                </Button>
              </Popconfirm>
              <div style={{ marginTop: 8 }}>
                <Text type="secondary" style={{ fontSize: 12 }}>
                  注意：此操作不可撤销，请谨慎操作
                </Text>
              </div>
            </div>
          </>
        )}
      </Card>
    </Modal>
  );
};

export default TopicAdminPanel; 